package cn.framework.mail.converter;
 
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import cn.framework.mail.model.Mail;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jms.support.converter.MessageConverter;


 
/**
 * Converte User message.
 * 
 * @author Yangtze
 */
public class MailConverter implements MessageConverter{
 
    private static transient Log logger = LogFactory.getLog(MailConverter.class);
 
    /* (non-Javadoc)
	 * @see com.trendcom.jms.converter.MailConverter#fromMessage(javax.jms.Message)
	 */
    public Object fromMessage(Message message) throws JMSException {
        if (logger.isDebugEnabled()) {
            logger.debug("Receive JMS message: " + message);
        }
 
        if (message instanceof ObjectMessage) {
            ObjectMessage oMsg = (ObjectMessage) message;
 
            if (oMsg instanceof ActiveMQObjectMessage) {
                ActiveMQObjectMessage aMsg = (ActiveMQObjectMessage) oMsg;
 
                try {
                    Mail mail = (Mail) aMsg.getObject(); 
                    return mail;
                } catch (Exception e) {
                    logger.error("Message:[" + message + "] is not a instance of User.");
                    throw new JMSException("Message:[" + message + "] is not a instance of User.");
                }
            } else {
                logger.error("Message:[" + message + "] is not " 
				    + "a instance of ActiveMQObjectMessage[User].");
                throw new JMSException("Message:[" + message + "] is not " 
				    + "a instance of ActiveMQObjectMessage[User].");
            }
        } else {
            logger.error("Message:[" + message + "] is not a instance of ObjectMessage.");
            throw new JMSException("Message:[" + message + "] is not a instance of ObjectMessage.");
        }
    }
 
    /* (non-Javadoc)
	 * @see com.trendcom.jms.converter.MailConverter#toMessage(java.lang.Object, javax.jms.Session)
	 */
    public Message toMessage(Object obj, Session session) throws JMSException {
        if (logger.isDebugEnabled()) {
            logger.debug("Convert User object to JMS message: " + obj);
        }
 
        if (obj instanceof Mail) {
            ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
            msg.setObject((Mail) obj);

            return msg;
        } else {
            logger.error("Object:[" + obj + "] is not a instance of User.");
            throw new JMSException("Object:[" + obj + "] is not a instance of User.");
        }
    }
}